package org.rsbot.gui;

import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;

import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;

import org.rsbot.util.GlobalConfiguration;

/*
 *  Modified 26.9.2010 by Waterwolf
 *   -Instead of netbeans' crap GUI it uses AbstractLayout
 *   -Instead of move up/down buttons items can be now dragged inside JList
 *   -Shows in log if saving custom rewards failed or succeeded
 *   -When saving to file, gets JList values from DefaultListModel instead of String[] choices
 *   Note: old netbeans gui methods are commented incase someone really wants them back (i dont know why though, they're way harder to modify than hand coded GUI's)
 *
 *  Version 1.0:
 * 		Place most wanted rewards on top, least on bottom.
 * 		Using the ScrollBox, select the skill you want XP for if you get XP as a reward.
 * 		@author Sorcermus 08-30-2010
 */
public class PickRewardsGUI extends JInternalFrame {

    private static final long serialVersionUID = 1L;
    String os = System.getProperty("os.name");
    String filename;
    static File PickRewardsFile;
    String[] choices = {"Cash", "Runes", "Coal", "Essence", "Ore", "Bars", "Gems", "Herbs", "Seeds", "Charms", "XP item", "Surprise", "Emote", "Costume", "Drop"};
    String XPChoice = "Attack";
    private JButton Save;
    private JComboBox jComboBox1;
    private JList jList1;
    /*
    private JScrollPane jScrollPane1;
    private JButton moveDown;
    private JButton moveUp;
     */
    private JLabel jLabel1;
    private JLabel jLabel15;
    private JLabel jLabel18;
    private JLabel jLabel2;
    private JLabel jLabel3;
    private JLabel jLabel4;
    private JLabel jLabel5;
    private JLabel jLabel6;
    private JLabel jLabel7;
    private JLabel jLabel8;
    private JLabel jLabel9;
    private JPanel jPanel1;
    final DefaultListModel model = new DefaultListModel();

    public PickRewardsGUI() {
        try {
            setFrameIcon(new ImageIcon(GlobalConfiguration.RUNNING_FROM_JAR ? getClass().getResource(GlobalConfiguration.Paths.Resources.REWARD) : new File(GlobalConfiguration.Paths.REWARD).toURI().toURL()));
        } catch (final MalformedURLException e1) {
        }
        filename = new File(GlobalConfiguration.Paths.getSettingsDirectory()) + File.separator + "PRds";
        PickRewardsFile = new File(filename);
        if (PickRewardsFile.exists()) {
            try {
                BufferedReader in = new BufferedReader(new FileReader(filename));
                String inputLine = "";
                int choicenumber = 0;
                while ((inputLine = in.readLine()) != null) {
                    if (choicenumber > (choices.length - 1)) {
                        XPChoice = inputLine;
                        break;
                    }
                    choices[choicenumber] = inputLine;
                    choicenumber++;
                }
            } catch (final Exception e) {
                e.printStackTrace();
            }

        }

        jPanel1 = new JPanel(null);
        //GridBagConstraints c = new GridBagConstraints();
        //jScrollPane1 = new JScrollPane();
        jList1 = new JList();
        //moveUp = new JButton();
        //moveDown = new JButton();
        Save = new JButton();
        jComboBox1 = new JComboBox();
        jLabel1 = new JLabel();
        jLabel2 = new JLabel();
        jLabel3 = new JLabel();
        jLabel4 = new JLabel();
        jLabel5 = new JLabel();
        jLabel6 = new JLabel();
        jLabel7 = new JLabel();
        jLabel8 = new JLabel();
        jLabel9 = new JLabel();
        jLabel15 = new JLabel();
        jLabel18 = new JLabel();

        setTitle("Custom Reward Box Choices");
        jPanel1.setBorder(BorderFactory.createTitledBorder(" Reward Box Choices "));


        for (String choice : choices) {
            model.addElement(choice);
        }

        jList1.setModel(model);

        MouseAdapter handler = new MouseAdapter() {

            private int index;

            public void mousePressed(MouseEvent e) {
                index = getIndexAt(e.getPoint());
                setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                setCursor(Cursor.getDefaultCursor());
            }

            public void mouseDragged(MouseEvent e) {
                Point p = e.getPoint();
                int newIndex = getIndexAt(p);
                if (newIndex > -1 && index != newIndex) {
                    Object element = model.remove(index);
                    model.add(newIndex, element);
                    jList1.setSelectedIndex(newIndex);
                    index = newIndex;
                }
            }

            private int getIndexAt(Point p) {
                for (int i = jList1.getFirstVisibleIndex(); i <= jList1.getLastVisibleIndex(); i++) {
                    if (jList1.getCellBounds(i, i).contains(p)) {
                        return i;
                    }
                }
                return -1;
            }
        };
        jList1.addMouseListener(handler);
        jList1.addMouseMotionListener(handler);

        /*Dimension listSize = new Dimension(80, 250);

        jList1.setMinimumSize(listSize);
        jList1.setPreferredSize(listSize);*/

        Save.setText("Save");
        Save.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent evt) {
                SaveActionPerformed(evt);
            }
        });

        jLabel1.setText("This is a priority list. On");
        jLabel2.setText("the left highlight what you");
        jLabel3.setText("want. By dragging selected");
        jLabel4.setText("item, move it to show your");
        jLabel5.setText("next choice if the first is");
        jLabel6.setText("not avalable. The client will");
        jLabel7.setText("go down the list & pick the");
        jLabel8.setText("first thing that's a choice");
        jLabel9.setText("in the reward box.");
        jLabel15.setText("Below choose the skill you want xp on");
        jLabel18.setText("Must Save for changes to take effect");
        jComboBox1.setModel(new DefaultComboBoxModel(new String[]{"Attack", "Strength", "Defence", "Ranged", "Prayer", "Magic", "Runecrafting", "Construction", "Dungeoneering", "Hitpoints", "Agility", "Herblore", "Thieving", "Crafting", "Fletching", "Slayer", "Hunter", "Mining", "Smithing", "Fishing", "Cooking", "Firemaking", "Woodcutting", "Farming", "Summoning"}));
        jComboBox1.setSelectedItem(XPChoice);

        Insets insets = jPanel1.getInsets();

        Point listLocation = new Point(5, 5);
        Dimension listSize = new Dimension(75, 250);

        setComponentAt(jPanel1, insets, jList1, listLocation.x, listLocation.y, listSize.width, listSize.height);

        int textX = 85;
        int textY = 5;

        int textW = 150;
        int textH = 15;

        int spaceBetween = 20;

        setComponentAt(jPanel1, insets, jLabel1, textX, textY, textW, textH);
        setComponentAt(jPanel1, insets, jLabel2, textX, textY += spaceBetween, textW, textH);
        setComponentAt(jPanel1, insets, jLabel3, textX, textY += spaceBetween, textW, textH);
        setComponentAt(jPanel1, insets, jLabel4, textX, textY += spaceBetween, textW, textH);
        setComponentAt(jPanel1, insets, jLabel5, textX, textY += spaceBetween, textW, textH);
        setComponentAt(jPanel1, insets, jLabel6, textX, textY += spaceBetween, textW, textH);
        setComponentAt(jPanel1, insets, jLabel7, textX, textY += spaceBetween, textW, textH);
        setComponentAt(jPanel1, insets, jLabel8, textX, textY += spaceBetween, textW, textH);
        setComponentAt(jPanel1, insets, jLabel9, textX, textY += spaceBetween, textW, textH);

        int otherTextBaseY = (listLocation.y + listSize.height + 5);

        setComponentAt(jPanel1, insets, jLabel15, 5, otherTextBaseY, 250, 15);
        setComponentAt(jPanel1, insets, jComboBox1, 3, otherTextBaseY += 15, 200, 20);

        setComponentAt(jPanel1, insets, jLabel18, 5, otherTextBaseY += 25, 250, 15);
        setComponentAt(jPanel1, insets, Save, 3, otherTextBaseY += 15, 200, 20);

        /*jList1.setBounds(10 + insets.left, 5 + insets.top,
        90, 250);
        jList1.setBounds(10 + insets.left, 5 + insets.top,
        90, 250);


        jPanel1.add(jList1);*/


        /*
        GroupLayout jPanel1Layout = new GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
        .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
        .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.TRAILING, false)
        .addComponent( jLabel15, GroupLayout.Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addGroup(GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
        .addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 76, GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
        .addComponent(moveDown, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(moveUp, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(jLabel9, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(jLabel8, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(jLabel7, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(jLabel6, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(jLabel5, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(jLabel4, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(jLabel3, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(jLabel2, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(jLabel1, GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE))))
        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE))
        .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.TRAILING, false)
        .addComponent( Save, GroupLayout.Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent( jLabel18, GroupLayout.Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent( jComboBox1, GroupLayout.Alignment.LEADING, 0, 203, Short.MAX_VALUE)))
        .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
        .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
        .addGroup(jPanel1Layout.createSequentialGroup()
        .addComponent(jLabel1)
        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jLabel2)
        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jLabel3)
        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jLabel4)
        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jLabel5)
        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jLabel6)
        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jLabel7)
        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jLabel8)
        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jLabel9)
        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(moveUp)
        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(moveDown))
        .addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 250, GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jLabel15)
        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jComboBox1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jLabel18)
        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(Save)
        .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
         */
        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE).addContainerGap()));
        layout.setVerticalGroup(
                layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE).addContainerGap(5, Short.MAX_VALUE)));

        pack();
        setVisible(true);
    }

    public void setComponentAt(JPanel pane, Insets in, Component co, int x, int y, int w, int h) {
        co.setBounds(x + in.left, y + in.top,
                w, h);
        pane.add(co);
    }

    private void SaveActionPerformed(ActionEvent evt) {
        SaveSettings();
    }

    public void SaveSettings() {
        try {
            final BufferedWriter out = new BufferedWriter(new FileWriter(PickRewardsFile));
            for (int i = 0; i < model.getSize(); i++) {
                out.append(model.get(i).toString());
                out.newLine();
            }
            out.append("" + jComboBox1.getSelectedItem());
            out.close();
            //BotGUI.log.info("Custom reward settings succesfully saved");
        } catch (final IOException e) {
            //BotGUI.log.warning("Something went wrong in saving reward settings: " + e.getMessage());
        }
    }
}
